package com.example.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Random;

@Aspect
@Component
public class OrderAspect {

    // 1. 前置增强
    @Before("execution(* com.example.service.OrderServiceImpl.*(..))")
    public void beforeAdvice(JoinPoint joinPoint) {
        System.out.println("hello, 我是一个前置增强");
    }

    // 2. 后置增强（仅对add和delete方法）
    @AfterReturning("execution(* com.example.service.OrderServiceImpl.add(..)) || execution(* com.example.service.OrderServiceImpl.delete(..))")
    public void afterReturningAdvice() {
        System.out.println("bye, 我是一个后置增强");
    }

    // 3. 获取方法返回值
    @AfterReturning(pointcut = "execution(* com.example.service.OrderServiceImpl.*(..))", returning = "result")
    public void afterReturningWithResult(Object result) {
        if (result != null) {
            System.out.println("方法返回值: " + result);
        }
    }

    // 4. 计算方法执行时间
    @Around("execution(* com.example.service.OrderServiceImpl.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        long endTime = System.currentTimeMillis();
        System.out.println("方法执行时间: " + (endTime - startTime) + "毫秒");
        return result;
    }

    // 5. 权限校验（仅对add和delete方法）
    @Before("execution(* com.example.service.OrderServiceImpl.add(..)) || execution(* com.example.service.OrderServiceImpl.delete(..))")
    public void checkPermission(JoinPoint joinPoint) {
        Random random = new Random();
        int permission = random.nextInt(2); // 生成0或1

        if (permission == 0) {
            System.out.println("权限校验通过");
        } else {
            System.out.println("权限校验失败，无权限操作");
            throw new RuntimeException("无权限执行此操作");
        }
    }
}
